//
//  SendViewController.m
//  CloudWeibo
//
//  Created by CLOUD on 1/27/15.
//  Copyright (c) 2015 Cloud. All rights reserved.
//

#import "SendViewController.h"
#import "NearByViewController.h"
#import "UIFactory.h"
#import "BaseNavigationController.h"

@interface SendViewController ()

@end

@implementation SendViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardShowNotification:) name:UIKeyboardWillShowNotification object:nil];
        self.isCancelButton = YES;
        self.isBackButton = NO;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"发布新微博";
    _buttons = [[NSMutableArray alloc] initWithCapacity:6];

    UIButton *sendButton = [UIFactory createNavigationButton:CGRectMake(0, 0, 45, 30) title:@"发布" target:self action:@selector(sendAction)];
    UIBarButtonItem *sendBarButton = [[UIBarButtonItem alloc] initWithCustomView:sendButton];
    self.navigationItem.rightBarButtonItem = [sendBarButton autorelease];
    
    [self _initViews];
}

- (void)_initViews
{
    
    [self.textView becomeFirstResponder];
    
    NSArray *imageNames = [NSArray arrayWithObjects:
                           @"compose_locatebutton_background.png",
                           @"compose_camerabutton_background.png",
                           @"compose_trendbutton_background.png",
                           @"compose_mentionbutton_background.png",
                           @"compose_emoticonbutton_background.png",
                           @"compose_keyboardbutton_background.png",
                           nil];
    NSArray *hightedImageNames = [NSArray arrayWithObjects:
                                  @"compose_locatebutton_background_highlighted.png",
                                  @"compose_camerabutton_background_highlighted.png",
                                  @"compose_trendbutton_background_highlighted.png",
                                  @"compose_mentionbutton_background_highlighted.png",
                                  @"compose_emoticonbutton_background_highlighted.png",
                                  @"compose_keyboardbutton_background_highlighted.png",
                                  nil];
    for (int i=0; i<imageNames.count; i++) {
        NSString *imageName = [imageNames objectAtIndex:i];
        NSString *hightedImageName = [hightedImageNames objectAtIndex:i];
        UIButton *button = [UIFactory createButton:imageName highlited:hightedImageName];
        
        [button setImage:[UIImage imageNamed:hightedImageName] forState:UIControlStateSelected];
        //[button setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
        button.tag = (10+i);
        [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        button.frame = CGRectMake(20+(64*i), 25, 23, 19);
        [self.editorBar addSubview:button];
        if (i == 5) {
            button.hidden = YES;
            button.left = button.left - 64;
        }
        [_buttons addObject:button];
    }
    
    UIImage *image = [self.placeBackgroundView.image stretchableImageWithLeftCapWidth:30 topCapHeight:0];
    self.placeBackgroundView.image = image;
    self.placeBackgroundView.width = 200;
    self.placeLabel.left = 35;
    self.placeLabel.width = 160;
    
    
}

- (void)location
{
    NearByViewController *nearby = [[NearByViewController alloc] init];
    BaseNavigationController *nearbyNav = [[BaseNavigationController alloc] initWithRootViewController:nearby];
    [self presentViewController:nearbyNav animated:YES completion:NULL];
    [nearby release];
    [nearbyNav release];
    nearby.selectBlock = ^(NSDictionary *dic){
        self.longitude = [dic objectForKey:@"lon"];
        self.latitude = [dic objectForKey:@"lat"];
        NSString *address = [dic objectForKey:@"address"];
        if ([address isKindOfClass:[NSNull class]] || address.length == 0) {
            address = [dic objectForKey:@"title"];
        }
        
        self.placeView.hidden = NO;
        self.placeLabel.text = address;
    };
    
    UIButton *locationButton = [_buttons objectAtIndex:0];
    locationButton.selected = YES;
}


- (void)selectImage
{
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"拍照" otherButtonTitles:@"相册", nil];
    [actionSheet showInView:self.view];
    [actionSheet release];
}

- (void)buttonAction:(UIButton *) button
{
    if (button.tag == 10) {
        [self location];
    } else if (button.tag == 11) {
        [self selectImage];
    }
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    UIImagePickerControllerSourceType sourceType;
    if (buttonIndex == 0) {
        BOOL isCamera = [UIImagePickerController isCameraDeviceAvailable:(UIImagePickerControllerCameraDeviceRear)];
        if (!isCamera) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"没有摄像头" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alertView show];
            [alertView release];
            return;
        }
        sourceType = UIImagePickerControllerSourceTypeCamera;
    }else if(buttonIndex == 1) {
        sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }else if(buttonIndex ==2) {
        return;
    }
    
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.sourceType = sourceType;
    imagePicker.delegate = self;
    [self presentViewController:imagePicker animated:YES completion:NULL];
    [imagePicker release];
}


- (void)textViewDidChange:(UITextView *)textView
{
    self.sendImageButton.top = self.textView.contentSize.height;
    self.deleteButton.top = self.textView.contentSize.height;
    
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *sendImage = [info objectForKey:UIImagePickerControllerOriginalImage];
    self.sendImage = sendImage;
    
    if (self.sendImageButton == nil) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.layer.masksToBounds = YES;
        button.frame = CGRectMake(10, self.textView.contentSize.height, 80, 80);
        [button addTarget:self action:@selector(imageBig:) forControlEvents:UIControlEventTouchUpInside];
        self.sendImageButton = button;
    }
    
    [self.sendImageButton setImage:self.sendImage forState:UIControlStateNormal];
    
    UIButton *delButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [delButton setImage:[UIImage imageNamed:@"action_delete.gif"] forState:UIControlStateNormal];
    delButton.frame = CGRectMake(self.sendImageButton.right-16, self.sendImageButton.top, 16, 16);
    [delButton addTarget:self action:@selector(deleteSendImage:) forControlEvents:UIControlEventTouchUpInside];
    self.deleteButton = delButton;
    
    [self.textView addSubview:self.sendImageButton];
    
    [self.textView addSubview:self.deleteButton];
    
    [picker dismissViewControllerAnimated:YES completion:NULL];
}

- (void)deleteSendImage:(UIButton *)button
{
    [self.sendImageButton removeFromSuperview];
    [button removeFromSuperview];
    self.sendImage = nil;
    self.textView.contentInset = UIEdgeInsetsMake(0.0f, 0.0f, 0.0f, 0.0f);
}

- (void)imageBig:(UIButton *)button
{
    if (_fullImageView == nil) {
        _fullImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
        _fullImageView.backgroundColor = [UIColor blackColor];
        _fullImageView.userInteractionEnabled = YES;
        _fullImageView.contentMode = UIViewContentModeScaleAspectFit;
        
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageSmall:)];
        
        [_fullImageView addGestureRecognizer:tapGesture];
        
        [tapGesture release];
    }
    
    if (![_fullImageView superview]) {
        _fullImageView.image = self.sendImage;
        
        [self.view.window addSubview:_fullImageView];
        
        [self.textView resignFirstResponder];
        _fullImageView.frame = CGRectMake(10, self.editorBar.top-20, 80, 80);
        [UIView animateWithDuration:.4 animations:^{
            _fullImageView.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight);
        } completion:^(BOOL finished){
            [UIApplication sharedApplication].statusBarHidden = YES;
        }];
        
    }
    
}

- (void)imageSmall:(UITapGestureRecognizer *)tapGesture
{
    [UIApplication sharedApplication].statusBarHidden = NO;
    [self.textView becomeFirstResponder];
    [UIView animateWithDuration:.4 animations:^{
        _fullImageView.frame = CGRectMake(10, self.editorBar.top-20, 80, 80);
    } completion:^(BOOL finished){
        [_fullImageView removeFromSuperview];
    }];
}

- (void)keyboardShowNotification:(NSNotification *)notification
{
    NSValue *keyboardRect = [notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect frame = [keyboardRect CGRectValue];
    float height = frame.size.height;
    self.editorBar.bottom = ScreenHeight - height - 20 - 44;
    self.textView.height = self.editorBar.top;
    if (self.sendImage != nil) {
        self.textView.contentInset = UIEdgeInsetsMake(0.0f, 0.0f, 90.0f, 0.0f);
    }
}


- (void)doSendData
{
    
    [super showStatusTip:YES title:@"发送中..."];
    
    NSString *text = self.textView.text;
    
    if (text.length == 0) {
        NSLog(@"微博内容不能为空");
        return;
    }
   
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObject:text forKey:@"status"];
    
    if (self.longitude.length > 0) {
        [params setObject:self.longitude forKey:@"long"];
    }
    
    if (self.latitude.length > 0) {
        [params setObject:self.latitude forKey:@"lat"];
    }
    if (self.sendImage == nil) {
        [self.sinaweibo requestWithURL:@"statuses/update.json" params:params httpMethod:@"POST" block:^(id result){
            [super showStatusTip:NO title:@"发送成功"];
            [self dismissViewControllerAnimated:YES completion:NULL];
        }];
    }else{
        NSData *data = UIImageJPEGRepresentation(self.sendImage, 0.3);
        
        [params setObject:data forKey:@"pic"];
        
        [self.sinaweibo requestWithURL:@"statuses/upload.json" params:params httpMethod:@"POST" block:^(id result){
            [super showStatusTip:NO title:@"发送成功"];
            [self dismissViewControllerAnimated:YES completion:NULL];
        }];
    }
    
}

- (void)sendAction
{
    [self doSendData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    [_textView release];
    [_editorBar release];
    [_placeView release];
    [_placeBackgroundView release];
    [_placeLabel release];
    [super dealloc];
}
@end
